package com.xkcoding.orm.jpa.service.impl;

import com.fasterxml.jackson.core.SerializableString;
import com.xkcoding.orm.jpa.entity.User;
import com.xkcoding.orm.jpa.entity.vo.UserVO;
import com.xkcoding.orm.jpa.repository.UserDao;
import com.xkcoding.orm.jpa.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.xkcoding.orm.jpa.utils.DtoTransformer.single;

@Service
public class UserServiceImpl implements UserService {

    @PersistenceContext
    private EntityManager entityManager;

    @Autowired
    private UserDao userDao;
    @Override
    public String getUserOne() {
        return userDao.findOne().getName();
    }

    @Override
    public Page<UserVO> queryPage(User vo, Integer currentPage, Integer pageSize) {
        if (null == currentPage) {
            return new PageImpl<>(new ArrayList<>(), PageRequest.of(currentPage - 1, pageSize), 0);
        }

        Pageable pageable = PageRequest.of(currentPage - 1, pageSize, Sort.Direction.DESC, "last_login_time");
        Page<User> page = userDao.queryPage(null, null,  pageable);
        return page.map(this::aaa);
    }

    public UserVO aaa(User task) {
        return single(UserVO.class, task);
    }

    @Override
    public Page<UserVO> queryPageObject(User vo, Integer currentPage, Integer pageSize) {
        if (null == currentPage) {
            return new PageImpl<>(new ArrayList<>(), PageRequest.of(currentPage - 1, pageSize), 0);
        }

        List<Sort.Order> orderList = new ArrayList<>();
        orderList.add(new Sort.Order(Sort.Direction.DESC, "last_login_time"));
        orderList.add(new Sort.Order(Sort.Direction.ASC, "id"));
        Pageable pageable = PageRequest.of(currentPage - 1, pageSize, Sort.by(orderList));

        Page<Object> page = userDao.queryPageObject(null, null,  pageable);

        List<UserVO> content = new ArrayList<>();
        if (!CollectionUtils.isEmpty(page.getContent())) {
            for (Object row : page.getContent()) {
                Object[] rowArray = (Object[]) row;
                UserVO vo1 = new UserVO();
                vo1.setName((String)rowArray[0]);
                content.add(vo1);
            }
        }
        return new PageImpl<>(content, pageable, page.getTotalElements());
    }



}
